﻿using DimensionsHelper.Common.Contracts.DataCollector;
using DimensionsHelper.Common.Contracts.Excel;
using DimensionsHelper.Common.Contracts.Services;
using DimensionsHelper.Common.Utils;

namespace DimensionsHelper.Client.ViewModels.DataCollector;

public partial class IndexFileViewModel(IServiceProvider serviceProvider) :
    ObservableCollection<FileViewModel>
{
    private int _index;

    public int Index
    {
        get => _index;
        set
        {
            if (_index == value)
            {
                return;
            }

            _index = value;
            OnPropertyChanged(new PropertyChangedEventArgs(nameof(Index)));
        }
    }


    private void AddNewFile(string fileName, string? expression = null)
    {
        FileViewModel? file = new()
        {
            FileName = fileName
        };

        if (!string.IsNullOrEmpty(expression))
        {
            file.Expression = expression;
        }

        Add(file);
    }


    [RelayCommand]
    private void AddNewEmptyFile()
    {
        AddNewFile(string.Empty);
    }


    [RelayCommand]
    private async Task SelectFile()
    {
        IReadOnlyList<string> files = await App.GetService<IFilePikerService>()!.
            PickMultipleFilesAsync(FileFilters.Excel);

        foreach (string? directory in files)
        {
            AddNewFile(directory);
        }
    }


    public void ToInputFiles(List<CollectorInputFile> targetList)
    {
        foreach (FileViewModel? item in this)
        {
            targetList.Add(new CollectorInputFile(
                Index,
                item.FileName,
                item.Expression,
                serviceProvider.GetRequiredService<IExcelWorkbookOperator>()));
        }
    }
}